var iot = require('iot');
var network = require('network');
var player = require('audioplayer');
var linkspeech = require('./linkspeech.js');

const productkey = 'productKey'; //your productkey
const devicename = 'deviceName'; //your devicename
const devicesecret = 'deviceSecret'; //your devicesecret

var tonepathPowerOn = "/resource/poweron.wav";
var tonepathConnected = "/resource/connected.wav";

console.log('\r\n----------------------- linkspeech application demo -----------------------\r\n');

player.setVolume(3);

var networkClient = network.openNetWorkClient();

var iotdev;

function iotDeviceCreate()
{
  iotdev = iot.device({
    productKey: productkey,
    deviceName: devicename,
    deviceSecret: devicesecret,
    keepaliveSec: 30
  });

  iotdev.on('connect', function() {
    console.log('success connect to aliyun iot server');
    player.play(tonepathConnected, function(){console.log('play ' + tonepathConnected + ' complete')});

    iotdev.onProps(function(res) {
      console.log('received cloud request len is ' + res.params_len);
      console.log('received cloud request is ' + res.params);
    });
  
    iotdev.onService(function(res) {
      console.log('received cloud msg_id is ' + res.msg_id);
      console.log('received cloud service_id is ' + res.service_id);
      console.log('received cloud params_len is ' + res.params_len);
      console.log('received cloud params is ' + res.params);
      linkspeech.process(0, iotdev, res.service_id, res.params);
    });
  });

  iotdev.on('close', function() {
    console.log('iot close');
  });

  iotdev.on('error', function(data) {
    console.log('error ' + data);
  });
}

player.play(tonepathPowerOn, function() {
  var netStatus = networkClient.getStatus();
  if (netStatus == 'connect') {
    iotDeviceCreate();
  } else {
    networkClient.on('connect', function() {
      iotDeviceCreate();
    });
  }
})